package blip.jcaf.cm.monitor;

import java.rmi.RemoteException;

import blip.jcaf.cm.BLIP_device_trackerActivity;
import blip.jcaf.cm.entity.PublicDisplay;
import dk.pervasive.jcaf.item.Location;
import dk.pervasive.jcaf.relationship.Located;
import dk.pervasive.jcaf.util.AbstractMonitor;

@SuppressWarnings("serial")
public class BLIPMonitor extends AbstractMonitor {
	
	String old_location = "";
	String new_location = "";
	private String btId;
	private BLIP_device_trackerActivity blip;
	private final static String _IP = "192.168.56.1"; //Change for multiple computers
	private final static String _URI = "rmi://"+_IP+"/blipTest";

	public BLIPMonitor(String btId) throws RemoteException {
			super(_URI);
			this.btId = btId;
			blip = new BLIP_device_trackerActivity(btId);
	}

	public String getMonitorInfo() {
		return "BLIP monitor";
	}

	public String getBluetoothId() {
		return btId;
	}
	
	public String getBtLocation() {
		return blip.getBlipLocation();
	}

	@Override
	public void monitor(String arg0) throws RemoteException {
		
	}

	@Override
	public void run() {
		int timeBuffer = 0;
		boolean startTimer = false;
		while(true) {
			try {
				new_location = blip.getBlipLocation();
				if(new_location != null) {
					if(!new_location.equals("toBeDefined") && !new_location.equals(old_location)) {
						getContextService().addContextItem(btId, new Located("BLIP"), new Location(btId, new_location));
						old_location = new_location;
						startTimer = true;
					} else if(timeBuffer >= 5) {
						//getContextService().removeContextItem(btId, new Located("BLIP"));
						getContextService().removeContextItem(btId, new Location(btId, old_location));
						startTimer = false;
					} else if(new_location != "toBeDefined") {
						timeBuffer = 0;
					} else if(new_location == "toBeDefined" && startTimer == true) {
						timeBuffer++;
						System.out.println("Time buffer increased: "+timeBuffer);
					}
				}
			} catch (RemoteException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			/*if(doThis == 1) {
				blip.setFakeBlipLocation("itu.zone4.zone4c");
			}
			if(doThis == 5) {
				blip.setFakeBlipLocation("itu.zone3.zone3b");
			}
			if(doThis == 10) {
				blip.setFakeBlipLocation(null);
			}
			if(doThis == 15) {
				blip.setFakeBlipLocation("itu.zone2.zone2d");
			}*/
			
			try {
				Thread.sleep(2000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
}
